package com.fancon.android.gardenjokesx.adapter;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.fancon.android.core.IFanconGlobalState;
import com.fancon.android.emoji.widget.RichTextView;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.ProfileActivity;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.ImageCacheView;

public class FriendsAdapter extends BaseAdapter implements SectionIndexer {
	private ArrayList<User> listFriends;
	private LayoutInflater inflater;
	private Activity mContext;
	private String user_id;

	public FriendsAdapter(Activity context, ArrayList<User> list, String userID) {
		this.listFriends = list;
		mContext = context;
		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		user_id = userID;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listFriends.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {
		final ViewHolder holder;
		View vi = convertView;
		if (vi == null) {
			vi = inflater.inflate(R.layout.common_item_list_friends, null);
			holder = new ViewHolder();
			// @binhbt-comment
			holder.imgAvatar = (ImageCacheView) vi
					.findViewById(R.id.common_img_friend_avatar);
			holder.txtName = (RichTextView) vi
					.findViewById(R.id.common_tv_Name);
			holder.txtUserName = (TextView) vi
					.findViewById(R.id.common_tv_UserName);
			holder.btnFollow = (Button) vi.findViewById(R.id.common_btn_Follow);
			vi.setTag(holder);
		} else {
			holder = (ViewHolder) vi.getTag();
		}
		// Gán dữ liệu của Item vào từng view
//		final User user = listFriends.get(position);
		// @binhbt-comment
		holder.imgAvatar.loadImage(StringUtil.processImageLink(listFriends.get(
				position).getUrl_image()));
		String str = listFriends.get(position).getFirst_name() + " "
				+ listFriends.get(position).getLast_name();
		if (str.trim().equals("")) {
			try {
				holder.txtName.setText(URLDecoder.decode(
						listFriends.get(position).getUser_name(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				holder.txtName.setText(URLDecoder.decode(str, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		holder.txtUserName.setText(listFriends.get(position).getUser_name());
		if (listFriends.get(position).isIs_following()) {
			holder.btnFollow
					.setBackgroundResource(R.drawable.common_btn_follow_active);
			holder.btnFollow.setText(mContext
					.getString(R.string.common_btn_following));
			//
			holder.btnFollow.setVisibility(View.VISIBLE);
		} else {
			if (listFriends.get(position).isIs_private()) {
//				holder.btnFollow
//						.setBackgroundResource(R.drawable.common_btn_request);
//				if (user.isIs_request()) {
//					holder.btnFollow.setText(mContext
//							.getString(R.string.common_waiting));
//				} else {
//					holder.btnFollow.setText(mContext
//							.getString(R.string.common_request));
//				}
				//do not allow follow when private
				holder.btnFollow.setVisibility(View.GONE);
			} else {
				holder.btnFollow.setVisibility(View.VISIBLE);
				holder.btnFollow
						.setBackgroundResource(R.drawable.common_btn_follow);
				holder.btnFollow.setText(mContext
						.getString(R.string.common_btn_follow));
			}
		}

		// Bắt sự kiện khi click nut Follow
		holder.btnFollow.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				User user = listFriends.get(position);
				Button followBtn = holder.btnFollow;
				if (user.isIs_following()) {
					// Sử dụng API 6.4 để đăng ký hủy follow
						//user.setIs_following(false);
						followBtn
								.setBackgroundResource(R.drawable.common_btn_follow);
						followBtn.setText(mContext
								.getString(R.string.common_btn_follow));
				} else {
					// Sử dụng API 6.4 để đăng ký following
						//user.setIs_following(true);
						followBtn
								.setBackgroundResource(R.drawable.common_btn_follow_active);
						followBtn.setText(mContext
								.getString(R.string.common_btn_following));
				}
				FollowRequest req = new FollowRequest("FollowRequest",
						(Activity) mContext, user, holder.btnFollow, user_id,
						user.getUser_id(), user.isIs_following() ? "false"
								: "true");
				((IFanconGlobalState) mContext).getRequestQueue().addRequest(
						req);
				Log.d("Following " + user.isIs_following(),
						"dsds" + user.isIs_following());
			}
		});
		vi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// @binhbt-comment
				Intent i = new Intent(mContext, ProfileActivity.class);
				i.putExtra(Constant.USER_ID_VIEW, listFriends.get(position)
						.getUser_id());
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				mContext.startActivity(i);
			}
		});
		return vi;
	}

	static class ViewHolder {
		ImageCacheView imgAvatar;
		RichTextView txtName;
		TextView txtUserName;
		Button btnFollow;
	}

	@Override
	public int getPositionForSection(int section) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public Object[] getSections() {
		// TODO Auto-generated method stub
		return null;
	}

	private Boolean registerFollow(String user_id, String following_user_id,
			String is_following) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("user_id", user_id));
		nameValuePairs.add(new BasicNameValuePair("following_user_id",
				following_user_id));
		nameValuePairs
				.add(new BasicNameValuePair("is_following", is_following));
		GardenJokesApiConnect api = new GardenJokesApiConnect(mContext);
		String str = api.execPost(mContext, GardenJokesApiConnect.GROUP_S,
				"registerFollowingUser", nameValuePairs);
		Log.d("json", "" + str);
		JsonPaser json = new JsonPaser();
		ReportErrors report = json.getReport(str);
		Log.d("ket qua dang ki", "" + report.getResult());
		return report.isIs_success();
	}

	class FollowRequest extends RequestUI {
		private String user_id, following_user_id, is_following;
		private Boolean result;
		private User user;
		private Button followBtn;

		public FollowRequest(Object key, Activity activity, User user,
				Button followBtn, String user_id, String following_user_id,
				String is_following) {
			super(key, activity);
			this.user_id = user_id;
			this.following_user_id = following_user_id;
			this.is_following = is_following;
			this.user = user;
			this.followBtn = followBtn;
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			result = registerFollow(user_id, following_user_id, is_following);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			Log.d("Result", "" + result);
			if (user.isIs_following()) {
				// Sử dụng API 6.4 để đăng ký hủy follow
				if (!result) {
					//user.setIs_following(false);
					followBtn
							.setBackgroundResource(R.drawable.common_btn_follow_active);
					followBtn.setText(mContext
							.getString(R.string.common_btn_following));
				}else{
					user.setIs_following(false);
				}
			} else {
				// Sử dụng API 6.4 để đăng ký following
				if (!result) {
					//user.setIs_following(true);
					followBtn
							.setBackgroundResource(R.drawable.common_btn_follow);
					followBtn.setText(mContext
							.getString(R.string.common_btn_follow));
				}else{
					user.setIs_following(true);
				}
			}
		}

	}
}
